//
//  PhotoViewerViewController.swift
//  新浪微博
//
//  Created by 李赛 on 15/5/21.
//  Copyright (c) 2015年 李赛. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD


private let reuseIdentifer = "PhotoCell"

class PhotoViewerViewController: UIViewController,UIScrollViewDelegate {

    // 图像的缩放比例
    var scale : CGFloat = 1
    
    // 显示图像的url
    var imageUrl : NSURL? {
        didSet {
            // 下载图像
            SVProgressHUD.show()
            // 清空之前的image
            imageView.image = nil
            
            SDWebImageManager.sharedManager().downloadImageWithURL(imageUrl!, options: nil, progress: nil) { (image, error, _, _, _) -> Void in
                SVProgressHUD.dismiss()
            
                if error != nil {
                    SVProgressHUD.showErrorWithStatus("加载图片错误")
                    return
                }
                self.setupImage(image)
            }
        }
    }
    
    // 计算图像的大小
    private func setupImage(image : UIImage) {
        // 重置scrollView的属性
//        resetScrollView()
        
        println("下载完成,图像大小是: \(image.size)")
        let size = scaleImageSize(image)
        println("缩放后的图像大小是: \(size)")
        
        // 设置图片
        imageView.image = image
        // 设置图像大小
        imageView.frame = CGRectMake(0, 0, size.width, size.height)
        
        // 判断长短图
        if size.height > view.bounds.height {
            // 长图 设置滚动区域
            scrollView.contentSize = size
        } else {
            // 设置滚动视图的缩进
            let top = (view.bounds.height - size.height) * 0.5
            scrollView.contentInset = UIEdgeInsetsMake(top, 0, 0, 0)
        }
    }
    
    // 重置 scrollView 的属性
    private func resetScrollView() {
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    
    /// 按照屏幕宽度计算缩放后的图像尺寸
    private func scaleImageSize(image : UIImage) -> CGSize {
        let scale = image.size.width / view.bounds.size.width
        let h = image.size.height / scale

        return CGSizeMake(view.bounds.size.width, h)
    }
    
    // 滚动视图
    lazy var scrollView : UIScrollView = {
        let sv = UIScrollView(frame: self.view.bounds)
        // 设置代理
        // 设置缩放比例  最大和最小
        sv.delegate = self
        sv.minimumZoomScale = 0.5
        sv.maximumZoomScale = 2
        return sv
    }()

    // 图像视图
    lazy var imageView : UIImageView = {
        let iv = UIImageView()
        
        // 添加手势
        let pinch = UIPinchGestureRecognizer(target: self, action: "pinch:")
        iv.addGestureRecognizer(pinch)
        
        // 让imageView 与用户交互
        iv.userInteractionEnabled = true
        
        return iv
    }()
    
    override func loadView() {
        view = UIView(frame: UIScreen.mainScreen().bounds)
//        view.backgroundColor = UIColor.redColor()
        // 添加滚动视图
        view.addSubview(scrollView)
        // 将图片视图添加到滚动视图中
        scrollView.addSubview(imageView)
    }
    
    /// scrollView 的代理    
    // 返回要缩放的视图
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    // 缩放完成 释放手势后调用
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView!, atScale scale: CGFloat) {
        // 判断正题缩放比例 < 1.0 说明交互式转场
        if scale < 1.0 {
            completeTransition(true)
            return
        }
        
        // 重新调整图像的间距
        // 计算顶部的间距值
        let top = (scrollView.frame.height - view.frame.height) * 0.5
        
        if top > 0 {
            scrollView.contentInset = UIEdgeInsetsMake(top, 0, 0, 0)
        }else {
            scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    /// 只要是缩放，就会调用
    /**
    结论：scrollView 是通过修改 视图的 transform 来实现的缩放
    
    var a: CGFloat  缩放比例
    var b: CGFloat
    var c: CGFloat
    var d: CGFloat  缩放比例
    var tx: CGFloat x位移
    var ty: CGFloat y位移
    
    a,b,c,d一起决定了旋转
    */
    func scrollViewDidZoom(scrollView: UIScrollView) {
        // 可以根据a的变化 来判断放大还是缩小
        if imageView.transform.a < 1.0 {
            scale = imageView.transform.a
            // 开始交互转场
            startInteractiveTransition(self)
        }
    }
    
    func pinch(gesture : UIPinchGestureRecognizer){
        self.scale = gesture.scale
        
        // 判断手势的状态
        /// 手势变化
        if gesture.state == UIGestureRecognizerState.Changed {
            let transform = CGAffineTransformMakeScale(scale, scale)
            
            // 缩小
            if scale < 1.0 {
                // 开始交互方式转场
                startInteractiveTransition(self)
            } else {
                imageView.transform = CGAffineTransformMakeScale(gesture.scale, gesture.scale)
            }
            
        }else if gesture.state == UIGestureRecognizerState.Ended || gesture.state == UIGestureRecognizerState.Cancelled {
            if scale < 0.5 {
                completeTransition(true)
            }
        }
    }
    
}

extension PhotoViewerViewController : UIViewControllerInteractiveTransitioning {
    /// 开始交互转场
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        // 将目标控制器的视图 添加到容器视图中
        let toViewVC = transitionContext.viewControllerForKey(UITransitionContextToViewKey)
        let toView = toViewVC!.view
        
        // snapshotViewAfterScreenUpdates 能够建立目标视图的快照
        let dummyView = toView.snapshotViewAfterScreenUpdates(false)
        
        transitionContext.containerView().insertSubview(dummyView, aboveSubview: view)
        
        // 将当前试图控制器的视图 alpha 降低
        view.transform = CGAffineTransformMakeScale(scale, scale)
        view.alpha = scale
        
    }
}

extension PhotoViewerViewController : UIViewControllerContextTransitioning {
    // 转场的容器视图
    func containerView() -> UIView {
        return view.superview!
    }
    
    // 是否转场结束
    func completeTransition(didComplete: Bool) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 参与转场的视图控制器
    func viewControllerForKey(key: String) -> UIViewController? {
        if key == UITransitionContextToViewKey {
            return UIApplication.sharedApplication().keyWindow!.rootViewController
        }else {
            return self
        }
    }
    // MARK: -  可以不用的函数
    func isAnimated() -> Bool {
        return true
    }
    
    func isInteractive() -> Bool {
        return true
    }
    
    func transitionWasCancelled() -> Bool {
        return false
    }
    
    func presentationStyle() -> UIModalPresentationStyle {
        return UIModalPresentationStyle.Custom
    }
    
    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition() {}
    func cancelInteractiveTransition() {}
    
    func viewForKey(key: String) -> UIView? {
        return nil
    }
    
    func targetTransform() -> CGAffineTransform {
        return CGAffineTransformIdentity
    }
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect {
        return CGRectZero
    }
    
    func finalFrameForViewController(vc: UIViewController) -> CGRect {
        return CGRectZero
    }

}
